package com.example.yiparkapplication.activity.index.activity.myCoupons;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.yiparkapplication.R;
import com.example.yiparkapplication.constant.API;
import com.example.yiparkapplication.constant.Constant;
import com.example.yiparkapplication.entity.MonthCard;
import com.example.yiparkapplication.util.BaseActivity;
import com.example.yiparkapplication.util.Common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyCouponsActivity extends BaseActivity implements View.OnClickListener {
    private Handler handler;
    private String mUserId;
    private String searchType;
    private String streetId;
    private String couponId;
    private String price;
    private List<MonthCard> mMonthCardList;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_coupons_layout);
        handler = new Handler();

        RelativeLayout relativeLayout = findViewById(R.id.id_receive_coupon_action);
        relativeLayout.setOnClickListener(this);
        SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
        mUserId = pref.getString("userId", "");
        searchType = "cardBag";
        Intent intent = getIntent();
        streetId = intent.getStringExtra("mRouteNameId");
        if (streetId != null && "".equals(streetId)){
            searchType = "CarOrder";
            relativeLayout.setVisibility(View.GONE);
            couponId = intent.getStringExtra("mCouponId");
            price = intent.getStringExtra("mPrice");
        }else{
            streetId = "";
        }

        getPlateVipList();
    }

    @Override
    public void onClick(View v){
        switch(v.getId()){
            case R.id.id_receive_coupon_action:
                Intent intent = new Intent(MyCouponsActivity.this, ReceiverCouponActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void getPlateVipList(){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request;
        if (couponId != null && !"".equals(couponId)){
            request = new Request.Builder()
                    .url(API.HOST + API.URL_GET_PLATEVIP_LIST + "?parkUserId=" + mUserId + "&streetid=" + streetId + "&couponId=" + couponId + "&price=" + price)
                    .build();
        }else{
            request = new Request.Builder()
                    .url(API.HOST + API.URL_GET_PLATEVIP_LIST + "?parkUserId=" + mUserId + "&streetId=" + streetId + "&price=" + price)
                    .build();
        }
        okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)throws IOException{
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    JSONArray object = joOut.getJSONArray("object");
                    mMonthCardList = new ArrayList<MonthCard>();
                    if (object != null){
                        for (int i=0;i< object.size(); i++){
                            JSONObject cardInfo = object.getJSONObject(i);
                            MonthCard monthCard = new MonthCard();
                            monthCard.setStartTime(cardInfo.getString("startTime"));
                            monthCard.setEndTime(cardInfo.getString("endTime"));
                            monthCard.setUsableTimes(cardInfo.getInteger("useableTimes"));
                            monthCard.setCouponId(cardInfo.getInteger("id"));
                            monthCard.setMonthCardName(cardInfo.getString("monthCardName"));
                            monthCard.setMonthDiscountType(cardInfo.getInteger("monthDiscountType"));
                            monthCard.setMonthDiscountValue(cardInfo.getDouble("monthDiscountValue"));
                            monthCard.setAccessLimit(cardInfo.getDouble("accessLimit"));
                            if ("CarOrder".equals(searchType)){
                                monthCard.setWhether(cardInfo.getInteger("whether"));
                                monthCard.setReason(cardInfo.getString("reason"));
                            }
                            mMonthCardList.add(monthCard);
                        }
                    }
                    new Thread(){
                        public void run(){
                            handler.post(runnableUi);
                        }
                    }.start();
                }
            }
        });
    }

    Runnable runnableUi = new Runnable(){
        @Override
        public void run(){
            RecyclerView vRecyclerView = findViewById(R.id.id_available_coupons_recyclerView);
            vRecyclerView.setLayoutManager(new LinearLayoutManager(MyCouponsActivity.this));
            MyCouponsAdepter adepter = new MyCouponsAdepter(mMonthCardList, MyCouponsActivity.this, searchType);
            vRecyclerView.setAdapter(adepter);

            RelativeLayout nullImg = findViewById(R.id.id_data_null_tip);
            if (mMonthCardList.size() > 0){
                nullImg.setVisibility(View.GONE);
            }else{
                nullImg.setVisibility(View.VISIBLE);
            }
        }
    };

    public void postCouponInfo(String monthCardName, String couponId, int monthDiscountType, double monthDiscountValue){
        Intent intent = new Intent();
        intent.putExtra("monthCardName", monthCardName);
        intent.putExtra("couponId", couponId);
        intent.putExtra("monthDiscountType", monthDiscountType);
        intent.putExtra("monthDiscountValue", monthDiscountValue);
        setResult(Constant.POST_COUPON_CODE, intent);
        finish();
    }

    @Override
    protected void onRestart(){
        super.onRestart();
        getPlateVipList();
    }

}
